/*
 * Created on 2005-5-16
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.haoxi.gateway.runner;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.Queue;


/**
 * @author Cloud
 * Preferences - Java - Code Style - Code Templates
 */

public abstract class AbsDaemon extends Thread {
    /**
     * Logger for this class
     */
    private static final Log log = LogFactory
            .getLog(AbsDaemon.class);
    
    private IRun[] queueThreads;
    
    private Queue queue;
    
    private int min_thread_count;
    private int max_thread_count;
    
    private QueueThreadCtl hereMonitor = null;
    
    protected String name;
    
    public AbsDaemon(Queue inQueue) {
        queue = inQueue;
    }
    
    abstract public IRun getThread();
    
    private IRun[] initThreads(Queue queue, int maxThreads) {
        if(queue == null || maxThreads <= 0) {
            return null;
        }
        
        IRun[] threads = new IRun[maxThreads];
        for(int i=0;i<maxThreads;i++) {
            threads[i] = getThread();
        }
        return threads;
    }
    
    public void run() {
        //set max threads
        hereMonitor = new QueueThreadCtl(max_thread_count,
                min_thread_count);
        
        log.debug(name + " Deamon init !!!");
        
        //init threads
        queueThreads = initThreads(queue, hereMonitor.GetMaxNum());
        
        if(queueThreads == null || queueThreads.length <= 0) {
            return;
        }
        
        int nSize = queueThreads.length;
        int i=0;
        for(;i<nSize;i++) {
            new Thread(queueThreads[i]).start();
            log.debug("IRun:" + queueThreads[i].getName() + " start !!!");
        }
        
        log.debug(name + " Deamon start:" + i + " threads !!!");
    }

    public int getMax_thread_count() {
        return max_thread_count;
    }

    public void setMax_thread_count(int max_thread_count) {
        this.max_thread_count = max_thread_count;
    }

    public Queue getQueue() {
        return queue;
    }

}
